<?php
class Comment{
	static function get($id=-1,$field="*",$where=""){
		try{
			$sql = "SELECT ".$field." FROM `comment`";
			if($id>=0){
				$sql.=" WHERE `id`='".$id."'";
			}else if($where!=""){
				$sql.=" WHERE ".$where;
			}
			return DB::query($sql);
		} catch(PDOException $e) {
			$data['msg'] = "Error: " . $e -> errorInfo() . " sql: " . $sql;
			$data['state'] = false;
			echo json_encode($data);
		}
	}
	
	static function set($data,$id=-1){
		try{
			$sql  	= "update `comment` set ";
			$comma	= "";
			$where 	= "";
			if($id!=""){
				$where = " WHERE `id`='".$id."'";
			}else{
				return false;
			}
			if(empty($data))return false;
			foreach ($data as $field => $value) {
				if(!empty($value)||$value==""){
					$sql.=$comma." `".$field."`='".$value."'";
					$comma = ",";
				}
			}
			$sql.=$where;
			DB::exec_($sql);
			return true;
		} catch(PDOException $e) {
			$data['msg'] = "Error: " . $e -> errorInfo() . " sql: " . $sql;
			$data['state'] = false;
			echo json_encode($data);
			return false;
		}
	}
	
	static function validate(){
		$res['state'] = true;
		$res['error'] = array();

		$p = $_POST;
		if(!(isset($p["text"]) && !empty($p["text"]) && strlen(utf8_decode($p["text"])) > 2 &&strlen(utf8_decode($p["text"])) < 1000)) {
			$res['state'] = false;
			$res['error']['text'] = 1;
		}
		return $res;
	}
	
	static function create(){
		$p = $_POST;
		foreach($p as $key => $value) {
			if(is_string($value)){
				$p[$key] = trim($value);
			}
		}
		$tidy_config = array( 
                     'clean' => true,
                     'show-body-only' => true,
                     'output-html'=>true
                     ); 

		$tidy = tidy_parse_string($p['text'], $tidy_config, 'UTF8'); 
		if ($tidy->errorBuffer) {
		   $tidy->cleanRepair();
			$p['text'] = $tidy;
		}
		DB::exec_("insert into `comment` (`level`,`title`, `text`, `author`,`creating_date`,`report`,`parent`) values ('".(isset($p['level'])?$p['level']:0)."','" . (isset($p['title'])?$p['title']:"NULL") . "','" . $p['text'] . "'," . $_SESSION['user']['person']['id'] . ",now(),'".$p['report']."',".($p['parent']?"'".$p['parent']."'":"NULL").")");
		$id 	= DB::query("select max(`id`) as `id` from `comment`");
		$comment = Comment::get($id[0]['id']);
		return array("html"=>Comment::getViewData(-1,-1,$comment),"parent"=>(isset($comment[0]['parent'])&&$comment[0]['parent']!=''&&$comment[0]['parent']!="NULL"?"comment_for_".$comment[0]['report']."_".$comment[0]['parent']."_commentToComment":""));
	}
	static function getCommentView($comment,$id){
		$author 			= Person::get("",$comment['author'],"","`name`,`surname`,`patronymic`,`id`");
		$comment['name'] 	= Person::getFio($author);
		$comment['logo'] 	= $author['users'][0]['logo'];
		$comment['width'] 	= "".(540+20-$comment['level']*20);
		$comment['level'] 	= "".($comment['level']*20);
		$comment['idPref'] 	= $id==-1?"commentToComment":"";
		$comment['comments']= isset($comment['comments'])?$comment['comments']:"";
		$comment['blockComment'] = "";
		if($comment['state']==-1){
			$comment['blockComment'] = " blockComment";
			$comment['text']="Данный комментарий был заблокирован Администратором...";
		}
		//Парсинг кнопок
		//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
					$buttons 			= array();
					if(User::checkAccess('admin')&&$comment['state']!=-1){
						$buttons['Блокировать'] = array("opt"=>array("icon"=>"trash","text"=>false,"postData"=>array("id"=>$comment['id'])),"action"=>"blockComment(opt,but)");
					}
					if((User::getState()==1||User::checkAccess('admin'))&&$id==-1&&$comment['state']!=-1){
						$buttons['Ответить'] = array("url"=>"comment/new_","opt"=>array("icon"=>"pencil","action"=>"load","target"=>"dialog","postData"=>array("id"=>$comment['id'],"form"=>true)));
					}
					$comment['buttons'] = Template::getButtons($buttons);
		//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
		return Template::parse('comment/main',$comment);
	}
	
	static function getChildren($c,$parents,$id){
		$res 			= "";
		$c['comments'] 	= "";
		if(isset($parents[$c['id']])&&count($parents[$c['id']])!=0){
			foreach ($parents[$c['id']] as $c_) {
				$c['comments'].=Comment::getChildren($c_,$parents,$id);
			}
			$res.=Comment::getCommentView($c,$id);
		}else{
			$res = Comment::getCommentView($c,$id);
		}
		return $res;
	}

	static function getViewData($report=-1,$id=-1,$comments=""){
		$empty 		= "Комментариев к данному докладу нет.";
		$newForm 	= "";
		$comments 	= $comments==""?Comment::get($id,"*","`report`='".$report."' ORDER BY `creating_date`"):$comments;
		$res 		= "";
		if($id==-1){
			$levels 	= array();
			$ids 		= array();
			$parents 	= array();
			foreach ($comments as $comment) {
				$ids[$comment['id']] = $comment;
				if(isset($comment['parent'])&&$comment['parent']!='')$parents[$comment['parent']][]=$comment;
			}
			foreach ($comments as $i => $comment) {
				if(isset($comment['level'])&&$comment['level']==1){
					$res.= Comment::getChildren($comment,$parents,$id);
				}
			}
		}else{
			foreach ($comments as $comment) {
				$res.=Comment::getCommentView($comment,$id);
			}
		}
		
		if((User::getState()==1||User::checkAccess('admin'))&&!($report==-1&&$id==-1)){
			if($id==-1){
				$data['report'] = $report;
				$data['parent'] = "";
				$data['level'] 	= "1";
				$data['idPref'] = ""; 
			}else{
				$data['report'] = $comment['report'];
				$data['parent'] = $id;
				$data['level'] 	= "".(((int)$comment['level'])+1)."";
				$data['idPref'] = "commentToComment";
			}
			$newForm = Template::parse('comment/new',$data);
		};
		
		if($res==""){
			$res = "<div class='p5 b ui-widget-content'>".$empty."</div>".$newForm;
		}else{
			$res = $res.$newForm;
		}
		return $res;
	}
} 
 
?>